//
//  YCShareActionSheet.m
//  DemoActionSheet
//
//  Created by tangkexiong on 16/3/8.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCShareActionSheet.h"

#define kTitleheight 40.f
#define kTitleIndicatorHeight 0.5f
#define kCellHeight 99.f
#define kCellWidth 100.f
#define kCancelHeight 59.f
#define kCancelIndicatorHeight 1.f

#pragma mark - YCShareActionSheetItem

@implementation YCShareActionSheetItem



@end

#pragma mark - YCShareActionSheetCell

@implementation YCShareActionSheetCell



@end

#pragma mark - YCShareActionSheetFlowLayout

@interface YCShareActionSheetFlowLayout : UICollectionViewLayout

@end

@implementation YCShareActionSheetFlowLayout

- (CGSize)collectionViewContentSize {
    NSInteger numForActionSheetItem = [self numForActionSheetItem];
    NSInteger numX = ((int)self.collectionView.frame.size.width)/kCellWidth;
    NSInteger numY = ((int)self.collectionView.frame.size.height)/kCellHeight;
    
    if (numX==0 || numY==0) {
        return CGSizeZero;
    }
    
    NSInteger page = numForActionSheetItem%(numX * numY)!=0 ? numForActionSheetItem/(numX * numY)+1 : numForActionSheetItem/(numX * numY);
    
    UIPageControl *pageCtrl = [self.collectionView.superview viewWithTag:101];
    pageCtrl.numberOfPages = page;
    
    return CGSizeMake(page*self.collectionView.frame.size.width, self.collectionView.frame.size.height);
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = self.collectionView.frame.size.width;
    CGFloat height = self.collectionView.frame.size.height;
    
    NSInteger numX = ((int)width)/kCellWidth;
    NSInteger numY = ((int)height)/kCellHeight;
    
    NSInteger curPage = indexPath.row / (numX * numY);
    NSInteger curIndexX = (indexPath.row % (numX * numY)) % numX;
    NSInteger curIndexY = (indexPath.row % (numX * numY)) / numX;
    
    CGFloat leftWidth = width - numX * kCellWidth;
    CGFloat leftHeight = height - numY * kCellHeight;
    
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    attributes.frame = CGRectMake(curPage*width+leftWidth/2+curIndexX*kCellWidth, leftHeight/2+curIndexY*kCellHeight, kCellWidth, kCellHeight);
    attributes.size = CGSizeMake(kCellWidth, kCellHeight);
    attributes.alpha = 1.0;
    attributes.center = CGPointMake(attributes.frame.origin.x + attributes.frame.size.width/2, attributes.frame.origin.y + attributes.frame.size.height/2);
    
    return attributes;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSInteger numForActionSheetItem = [self numForActionSheetItem];
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (int i = 0; i < numForActionSheetItem; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [array addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }
    
    return array;
}

- (NSInteger)numForActionSheetItem {
    if ([self.collectionView.dataSource respondsToSelector:@selector(numberOfSectionsInCollectionView:)]) {
        return [self.collectionView.dataSource collectionView:self.collectionView numberOfItemsInSection:0];
    } else {
        return 0;
    }
}

@end

#pragma mark - YCShareActionSheet

@interface YCShareActionSheet ()<UICollectionViewDataSource, UICollectionViewDelegate> {
    UIWindow *_window;
    UIWindow *_oldWindow;
    
    BOOL _isShowing;
}

@property (nonatomic, copy) NSString *title;
@property (nonatomic, retain) NSArray *itemArray;

@end

@implementation YCShareActionSheet

@synthesize title = _title;

#pragma mark - UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self _configView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)_configView {
    [self.view layoutIfNeeded];
    
    _myCollectionView.tag = 100;
    [_myCollectionView setCollectionViewLayout:[[YCShareActionSheetFlowLayout alloc] init]];
    [_myCollectionView registerNib:[UINib nibWithNibName:@"YCShareActionSheetCell" bundle:nil] forCellWithReuseIdentifier:@"cellAction"];
    _myCollectionView.dataSource = self;
    _myCollectionView.delegate = self;
    
    _myPageCtrl.tag = 101;
    _myPageCtrl.pageIndicatorTintColor = [UIColor lightGrayColor];
    _myPageCtrl.currentPageIndicatorTintColor = [UIColor grayColor];
    _myPageCtrl.hidesForSinglePage = YES;
    
    _titleLabel.text = _title;
}

#pragma mark - Rotation

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    
    [self _caculateActionViewHeight];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YCShareActionSheetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellAction" forIndexPath:indexPath];
    
    YCShareActionSheetItem *item = _itemArray[indexPath.row];
    [cell.imgView setImage:[UIImage imageNamed:item.mImg]];
    [cell.nameLabel setText:item.mName];
    
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger page = (NSInteger)(scrollView.contentOffset.x/_myCollectionView.frame.size.width+0.5);
    _myPageCtrl.currentPage = page;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([_myDelegate respondsToSelector:@selector(shareActionSheet:didSelectAtIndex:)]) {
        [self.myDelegate shareActionSheet:self didSelectAtIndex:indexPath.row];
    }
    
    [self _dismissAnimation];
}

#pragma mark - Private

- (void)_caculateActionViewHeight {
    [self.view layoutIfNeeded];
    
    CGFloat width = _myCollectionView.frame.size.width;
    
    NSInteger numX = ((int)width)/kCellWidth;
    
    CGFloat titleHeight = _title ? kTitleheight : 0.f;
    if (_itemArray.count > numX) {
        _constraintActionViewHeight.constant = titleHeight + kTitleIndicatorHeight + kCellHeight * 2 + kCancelHeight + kCancelIndicatorHeight;
        _constraintCollectionViewHeight.constant = kCellHeight * 2;
    } else {
        _constraintActionViewHeight.constant = titleHeight + kTitleIndicatorHeight + kCellHeight + kCancelHeight + kCancelIndicatorHeight;
        _constraintCollectionViewHeight.constant = kCellHeight;
    }
    _constraintActionViewBottomMargin.constant = _isShowing ? 0.f : -_constraintActionViewHeight.constant;
    
    [_myCollectionView.collectionViewLayout invalidateLayout];
    [self.view layoutIfNeeded];
}

- (void)_showAnimation {
    _constraintActionViewBottomMargin.constant = 0.f;
    _bgView.alpha = 0.f;
    [UIView animateWithDuration:0.3f animations:^{
        _bgView.alpha = 0.5f;
        
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        _isShowing = YES;
    }];
}

- (void)_dismissAnimation {
    _constraintActionViewBottomMargin.constant = -(_constraintActionViewHeight.constant);
    [UIView animateWithDuration:0.3 animations:^{
        _bgView.alpha = 0;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        _isShowing = NO;
        
        [_window resignKeyWindow];
        _window = nil;
        
        [_oldWindow makeKeyAndVisible];
    }];
}

#pragma mark - IBAction

- (IBAction)cancelBtnClicked:(id)sender {
    if ([_myDelegate respondsToSelector:@selector(shareActionSheetDidCancel:)]) {
        [_myDelegate shareActionSheetDidCancel:self];
    }
    
    [self _dismissAnimation];
}

#pragma mark - Public

+ (instancetype)instanceWithTitle:(NSString *)title shareItems:(NSArray *)itemArray delegate:(id<YCShareActionSheetDelegate>)delegate {
    YCShareActionSheet *sheet = [[YCShareActionSheet alloc] initWithNibName:@"YCShareActionSheet" bundle:nil];
    
    sheet.title = title;
    sheet.itemArray = itemArray;
    sheet.myDelegate = delegate;
    
    return sheet;
}

- (void)show {
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.windowLevel = 440.f;
    _window.rootViewController = self;
    _oldWindow = [UIApplication sharedApplication].keyWindow;
    [_window makeKeyAndVisible];
    
    _isShowing = NO;
    
    [self _caculateActionViewHeight];
    
    [self _showAnimation];
}

@end
